/*
 * @Description: 工具
 * @Author: wang_k
 * @Date: 2025-04-25 15:56:46
 * @LastEditTime: 2025-04-25 16:01:21
 * @FilePath: /vue-project/src/utils/index.js
 */
export function restructureRoutes(routes) {
  const rootRoutes = [];
  const routeMap = new Map();
  const childrenCount = new Map();

  // 初始化路由映射
  routes.forEach(route => {
    routeMap.set(route.path, { ...route });
    childrenCount.set(route.path, 0);
  });

  // 统计每个路由的子路由数量
  routes.forEach(route => {
    const pathParts = route.path.split('/').filter(part => part);
    if (pathParts.length > 1) {
      const parentPath = '/' + pathParts.slice(0, -1).join('/');
      const count = childrenCount.get(parentPath) || 0;
      childrenCount.set(parentPath, count + 1);
    }
  });

  // 构建嵌套关系
  routes.forEach(route => {
    const pathParts = route.path.split('/').filter(part => part);
    if (pathParts.length === 1) {
      // 根路由
      rootRoutes.push(routeMap.get(route.path));
    } else {
      // 子路由
      const parentPath = '/' + pathParts.slice(0, -1).join('/');
      const parentRoute = routeMap.get(parentPath);
      if (parentRoute) {
        if (!parentRoute.children) {
          parentRoute.children = [];
        }
        parentRoute.children.push(routeMap.get(route.path));
      }
    }
  });

  // 移除没有子路由的路由的 children 字段
  function removeEmptyChildren(routeList) {
    routeList.forEach(route => {
      if (route.children && route.children.length === 0) {
        delete route.children;
      }
      if (route.children) {
        removeEmptyChildren(route.children);
      }
    });
  }
  removeEmptyChildren(rootRoutes);

  return rootRoutes;
}